<?php

namespace Lib;

class Jqgrid {

	public function ls2json($aList, $sIndex = 'id', $aMap = array()) {
		global $o;
		$aData = array (
				'page' => $aList ['page'],
				'records' => $aList ['count'],
				'total' => $aList ['pages'] 
		);
		if (is_array ( $aList ['items'] )) {
			foreach ( $aList ['items'] as $val ) {
				$aRow = array (
						'id' => $val [$sIndex] 
				);
				
				foreach ( $aMap as $v ) {
					if (is_array ( $v )) {
						if ($v ['model']) {
							$oObject = $o->Model->$v ['model'];
							$aRow ['cell'] [] = call_user_func_array ( array (
									$oObject,
									$v ['method'] 
							), array (
									$val 
							) );
						}
					} else {
						$aRow ['cell'] [] = $val [$v];
					}
				}
				
				$aData ['rows'] [] = $aRow;
			}
		}
		return json_encode ( $aData );
	}

	public function getValue($sModel, $sMethod, $sType, $aParam = array(), $aBefore = null) {
		global $o;
		$oObject = $o->Model->$sModel;
		$aResult = call_user_func_array ( array (
				$oObject,
				$sMethod 
		), $aParam );
		if ($sType == 'checkbox') {
			$aValue = array_values ( $aResult );
			return '\'' . $aValue [0] . ':' . $aValue [1] . '\'';
		} elseif ($sType == 'select') {
			if (is_array ( $aBefore )) {
				$aResult = $aBefore + $aResult;
			}
			return json_encode ( $aResult );
		}
	}

	public function getResult($aParam = array()) {
		global $o;
		if ($o->aError ['code'] == 0) {
			return json_encode ( array (
					'success' => true 
			) );
		} else {
			return json_encode ( array (
					'success' => false,
					'message' => $o->aError ['message'] 
			) + ( array ) $aParam );
		}
	}
}